#encoding:utf8

import sys
import os
import shutil
#import stat
import subprocess
import optparse
from lib import *

# 热舞启动参数
danceclient_startup_param	= 'game:pw:console:1 sepfile fullscreen:0  ignoreversion'

#######################################################################################
def check_connect_dance_source():
	'''
	check connect dance source
	'''
	remotename, user, password	= r'\\fnsourceserver', 'pw_prg_lixianmin', 'aWdtcXR0eHg='
	wsh.login(remotename, user, encrypt.decode(password))

#######################################################################################
def start_dance_client_release():
	'''Start a DanceClient.exe and attach it to windbg'''
	
	dirpath		= r'D:\me\document\VC6\DanceWorld\bin'
	os.chdir(dirpath)

	filename	= 'DanceClient.exe'
	filepath	= os.path.join(dirpath, filename)
	if os.path.exists(filepath):
		cmd	= 'windbg.exe -g %s %s'%(filepath, danceclient_startup_param)
		print('starting', filepath)
		subprocess.Popen(cmd)
		#print('starting', filepath, 'with pid=', p.pid)

	else:
		print('The specified file: ', filepath, 'does not exists')


#######################################################################################
def start_dance_client_debug():
	'''Start a DanceClient_d.exe'''
	dirpath	= r'D:\me\document\VC6\DanceWorld\bin'
	# we should change to dirpath, otherwise subprocess will can not find the file
	os.chdir(dirpath)

	filename= 'DanceClient_d.exe'
	filepath= os.path.join(dirpath, filename)

	if os.path.exists(filepath):
		cmd	= [filepath, danceclient_startup_param]
		p	= subprocess.Popen(cmd)
		print('starting', filepath, 'with pid=', p.pid)
	else:
		print('The specified file: ', filepath, 'does not exists')

#######################################################################################
def end_dance_client():
	'''Kill all DanceClint.exe and DanceClient_d.exe processes'''
	killnames	= ['danceclient_d.exe', 'danceclient.exe']

	for name in killnames:
		for p in ps.listall(name):
			print('Kill %s with pid= %s'%(p.name, p.pid))
			ps.kill(p.pid)

#######################################################################################
def start_log_folder():
	'''Open the logs directory of the DanceClient project'''
	dirpath	= r'D:\me\document\VC6\DanceWorld\bin\logs'
	os.startfile(dirpath)

#######################################################################################
def start_se():
	'''Open DanceWorld directory on the E: disk'''
	dirpath	= r'E:\game\《热舞派对》开发最新\element'
	os.startfile(dirpath)

#######################################################################################
def start_download():
	'''Download all new DanceWorld resources from \\\\fnsourceserver'''
	check_connect_dance_source()
	print('please see the new command window....')
	os.system('start rw_download.py')

#######################################################################################
def start_upload():
	'''Upload all new client resources to \\\\fnsourceserver'''
	check_connect_dance_source()
	print('please see the new command window....')
	os.system('start rw_upload.py')

#######################################################################################
def print_version():
	'''print current DanceClient verion'''
	filepath	= r'D:\me\document\VC6\DanceWorld\bin\Configs\release_version.txt'
	if os.path.exists(filepath):
		fileencoding= 'utf16'
		with open(filepath, encoding= fileencoding) as fin:
			line	= fin.readline()

			try:
				version	= int(line)
				print('当前热舞发布版本号为：', version)
			except Exception as ex:
				pass
		
	else:
		print('Can not find file:', filepath)

#######################################################################################
def start_updatedata():
	'''Update element data and start DanceClient'''

	import threading
	import time
	import win32api
	import win32gui
	import win32con

	# 该线程会去检测游戏的更新窗口，并自动选择更新
	class UpdateWindowCloser(threading.Thread):
		def __init__(self, pid):
			threading.Thread.__init__(self)
			self.pid	= pid

		def run(self):
			titles	= ('更新设置', '请选择', '请选择')
			sendKeys= (win32con.VK_RETURN, win32con.VK_TAB, win32con.VK_RETURN)
			stage	= 0

			while stage < len(titles):
				time.sleep(0.3)

				try:
					title	= titles[stage]
					hwnd	= win32gui.FindWindow('DWPatcherClass', title)
					if hwnd:
						win32gui.SetForegroundWindow(hwnd)

						# send key
						key	= sendKeys[stage]
						win32api.keybd_event(key, 0, 0, 0)
						win32api.keybd_event(key, 0, win32con.KEYEVENTF_KEYUP, 0)

						stage	+= 1
						#print(title)
				except:
					pass


	cmd		= r'E:\game\《热舞派对》开发最新\patcher\patcher.exe game:pw:console:1 sepfile fullscreen:0  ignoreversion'
	srcdir	= r'E:\game\《热舞派对》开发最新\element\data'
	destdir	= r'D:\me\document\VC6\DanceWorld\bin\data'
	backup	= r'D:\me\document\VC6\DanceWorld\bin\data_backup'

	print_version()
	pdata			= subprocess.Popen(cmd)
	windowCloser	= UpdateWindowCloser(pdata.pid)
	windowCloser.setDaemon(True)
	windowCloser.start()
	pdata.wait()
	
	#print(dir(windowCloser))
	# update element data
	if os.path.isdir(backup):
		shutil.rmtree(backup)
	shutil.move(destdir, backup)
	shutil.copytree(srcdir, destdir)
	

#######################################################################################
def start_notify():
	'''Notify update'''
	#text	= input('请输入消息内容\n>>>')
	#text	= text.strip()
	text	= '游戏更新'
	if text:
		receiver= 'tuqiang'
		rtx.sendmessage(receiver, text)
		print('Message sended to %s'%receiver)

#######################################################################################
def open_guild():
	'''Open iconset directory'''
	path	= r'D:\me\document\VC6\DanceWorld\bin\surfaces\IconSet'
	os.startfile(path)


#######################################################################################
def vc6build(dspfile, mode= 'release', isrebuild= False):

	# modeparam
	mode		= mode.lower()
	modeparam	= '"all - Win32 RELEASE"'
	if mode == 'debug':
		modeparam	= '"all - Win32 Debug"'
	elif mode == 'all':
		modeparam	= '"all - Win32 Debug" "all - Win32 Release"'

	#buildparam
	buildparam	= 'REBUILD' if isrebuild else 'BUILD'

	msdev		= os.path.join(os.getenv('msdevdir'), r'bin\msdev.exe')
	cmd			= '%s %s /MAKE %s /%s / NORECURSE'%(msdev, dspfile, modeparam, buildparam)
	subprocess.Popen(cmd)

def build():
	'''Build both Release and Debug version of DanceClient project'''
	dspfile	= r'D:\me\document\VC6\DanceWorld\DanceWorld.dsw'
	vc6build(dspfile, 'all')

def rebuild():
	'''Reuild both Release and Debug version of DanceClient project'''
	dspfile	= r'D:\me\document\VC6\DanceWorld\DanceWorld.dsw'
	vc6build(dspfile, 'all', True)

def itemsee():
	'''Build itemsee according to the newest element data header files'''
	dspfile	= r'D:\me\document\VC6\DanceWorld\ECItemSee\ECItemSee.dsp'
	vc6build(dspfile, 'release')
	
#######################################################################################
def main():
	if len(sys.argv)==1:
		dirpath	= r'D:\me\perfectworld\rwpd'
		os.startfile(dirpath)
		sys.exit()
	
	########################################	
	parser	= optparse.OptionParser()
	def _addParserOption(parser, *args, **kwargs):
		assert 'processor' in kwargs, 'There should be an processor'
		processor			= kwargs.pop('processor')

		kwargs['const']		= processor
		kwargs['action']	= 'store_const'
		kwargs['help']		= processor.__doc__

		parser.add_option(*args, **kwargs)

	_addParserOption(parser, '-d', processor= start_dance_client_debug)
	_addParserOption(parser, '-r', processor= start_dance_client_release)
	_addParserOption(parser, '-z', processor= end_dance_client)
	_addParserOption(parser, '--se', processor= start_se)
	_addParserOption(parser, '--log', processor= start_log_folder)
	_addParserOption(parser, '--upload', processor= start_upload)
	_addParserOption(parser, '--download', processor= start_download)
	_addParserOption(parser, '--data', processor= start_updatedata)
	#_addParserOption(parser, '--notify', processor= start_notify)
	_addParserOption(parser, '--build', processor= build)
	_addParserOption(parser, '--itemsee', processor= itemsee)
	_addParserOption(parser, '--rebuild', processor= rebuild)
	_addParserOption(parser, '--version', processor= print_version)
	_addParserOption(parser, '--guild', '--iconset', processor= open_guild)

	options, args	= parser.parse_args()
	isvalid			= False
	for processor in options.__dict__.values():
		if processor:
			print(processor.__doc__)
			print('-'*60)
			processor()
			isvalid	= True

	if not isvalid:
		parser.print_help()

if __name__=='__main__':
	main()
